package com.sky.sky_server.controller.user;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.sky.sky_common.result.Result;
import com.sky.sky_pojo.dto.OrderSubmitDTO;
import com.sky.sky_pojo.dto.OrderSubmitVO;
import com.sky.sky_pojo.entity.OrderQueryPage;
import com.sky.sky_pojo.entity.Orders;
import com.sky.sky_server.mapper.OrderMapper;
import com.sky.sky_server.service.impl.OrderServiceImpl;
import com.sky.sky_server.websocket.WebSocketServer;
import com.sky.sky_pojo.dto.OrderPaymentDTO;
import com.sky.sky_pojo.dto.OrderPaymentVO;

import jakarta.validation.Valid;

@RestController("userOrderController")
@RequestMapping("/user/order")
@Slf4j
public class OrderController {
    @Autowired
    private OrderServiceImpl orderServiceImpl;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 提交订单
     * @param orderSubmitDTO
     */
    @PostMapping("submit")
    public Result submitOrder(@RequestBody @Valid OrderSubmitDTO orderSubmitDTO) {
        log.info("提交订单，orderSubmitDTO：{}");
        // 地址簿id不能为空
        OrderSubmitVO orderSubmitVO = orderServiceImpl.submitOrder(orderSubmitDTO);
        return Result.success(orderSubmitVO);
    }

    /**
     * 订单支付(模拟跳过微信支付)
     */
    @PutMapping("/payment")
    public OrderPaymentVO payment(@RequestBody OrderPaymentDTO orderPaymentDTO) {
        log.info("订单支付，orderPaymentDTO：{}", orderPaymentDTO);
        
        // todo 模拟微信支付调用接口，返回支付结果
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("nonceStr", UUID.randomUUID().toString().replace("-", ""));
        jsonObject.put("paySign", "fake-pay-sign");
        jsonObject.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
        jsonObject.put("signType", "MD5");
        jsonObject.put("packageStr", "prepay_id=fake-prepay-id");

        // 查询订单的支付状态
        String orderNumber = orderPaymentDTO.getOrderNumber();
        Orders ordersDB = orderMapper.selectByNumber(orderNumber);
        if (ordersDB != null && ordersDB.getPayStatus() == Orders.PayStatus.PAID.getCode()) {
            throw new RuntimeException("订单已支付");
        }

        // 将jsonObject转换为VO
        OrderPaymentVO orderPaymentVO = jsonObject.toJavaObject(OrderPaymentVO.class);

        // 模拟支付成功
        paySuccess(orderPaymentDTO.getOrderNumber());

        return orderPaymentVO;
    }

    /**
     * 微信支付回调函数
     */
    @Transactional
    public void paySuccess(String outTradeNo) {
        // 根据订单号查询订单
        Orders orderDB = orderMapper.selectByNumber(outTradeNo);
        if(orderDB == null){
            throw new RuntimeException("订单不存在" + outTradeNo);
        }

        // tag 不要直接使用查询出来的额数据直接覆盖更新：新建对象只赋值必要字段再去更新 → 更安全
        // 更新支付后的订单状态，支付时间
        Orders orders = new Orders();
        orders.setId(orderDB.getId());
        orders.setPayStatus(Orders.PayStatus.PAID.getCode());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(Orders.OrderStatus.PENDING_RECEIVE.getCode());

        orderMapper.updateById(orders);

        // 通过websocket向客户端发送支付成功消息
        Map<String, Object> map = new HashMap<>();
        map.put("type", 1); // 1 表示来单提醒，2表示客户催单
        map.put("orderId", orderDB.getId());
        map.put("content", "订单号：" + outTradeNo);

        String json = JSON.toJSONString(map);
        log.info("向客户端发送支付成功消息：{}", json);
        webSocketServer.sendToAllClient(json);
        
    }

    /**
     * 根据订单号查询订单详情
     * @param orderVO
     * @return
     */
    @GetMapping("/orderDetail/{id}")
    public Result getOrderDetail(@PathVariable Long id) {
        log.info("根据订单号查询订单详情，订单号：{}", id);
        return Result.success(orderServiceImpl.getOrderDetail(id)); 
    }

    /**
     * 查询历史订单
     * @param userId
     * @return
     */
    @GetMapping("/historyOrders")
    public Result historyOrders(@Valid OrderQueryPage orderQueryPage) {
        log.info("查询历史订单orderQueryPage = {}", orderQueryPage);
        return Result.success(orderServiceImpl.historyOrders(orderQueryPage));
        
    }

    /**
     * 取消订单
     */
    @PutMapping("/cancel/{id}")
    public Result cancelOrder(@PathVariable Long id) {
        log.info("取消订单，订单号：{}", id);
        
        orderServiceImpl.cancelOrder(id);
        return Result.success();
    }

    /**
     * 客户催单
     */

     @GetMapping("/reminder/{id}")
     public Result reminderOrder(@PathVariable Long id) {
         log.info("客户催单，订单号：{}", id);
         orderServiceImpl.reminderOrder(id);
         return Result.success();
     }

     /**
      * 再来一单，和订单id相同的订单
      */
      @PostMapping("repetition/{id}")
      public Result repetitionOrder(@PathVariable Long id) {
          int res = orderServiceImpl.repetitionOrder(id);
          if (res > 0) {
              return Result.success("再来一单成功");
          }
          return Result.error();
      }
}
